<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" style="margin-bottom:20px">
      <span style="margin-left:10px">市场人员姓名：</span>
      <el-input @keyup.enter.native="searchMarketers" style="width: 200px;" class="filter-item" placeholder="请输入院校名称" v-model="listQuery.marketerName" clearable></el-input>
      <span style="margin-left:10px">市场人员手机号：</span>
      <el-input @keyup.enter.native="searchMarketers" style="width: 200px;" class="filter-item" placeholder="请输入院校名称" v-model="listQuery.marketerMobile" clearable></el-input>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="searchMarketers">搜索</el-button>
      <!-- <el-button class="filter-item addAcademy"  type="success" icon="el-icon-plus" @click="addAcademy">新增院校</el-button> -->
    </div>
    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="数据加载中，请稍后" border fit highlight-current-row style="width: 100%">
      <el-table-column v-if='showAllDel' type="selection" width="55" />
      <el-table-column min-width="120" align="center" label="市场人员ID" prop="marketerId" />
      <el-table-column min-width="120" align="center" label="姓名" prop="marketerName" />

      <el-table-column align="center" label="操作" min-width="160">
        <template slot-scope="{row}">
          <el-button size="small" type="primary" @click="handleModifyStatus(row);">查看编辑关联高中</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo" :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="编辑关联高中" width="90%" :visible.sync="dialogFormVisible" center v-if="dialogFormVisible" >
    <el-row class="content">
    <el-col :span="11">
      <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false" type="primary">返回市场人员列表</el-button>
    </div>
    <div class="line"><span style="margin-left:10px">已经关联的高中：</span></div>
       <el-table
  ref="multipleTable"
  :data="haveSchool"
  tooltip-effect="dark"
  style="width: 100%"
  @selection-change="handleSelectionChange_have">
  <el-table-column
    type="selection"
    width="100">
  </el-table-column>
  <el-table-column
    label="高中ID"
    width="120">
    <template slot-scope="scope">{{ scope.row.schoolId }}</template>
  </el-table-column>
  <el-table-column
    prop="title"
    label="高中名称"
    width="300">
  </el-table-column>
      <el-table-column align="center" label="操作" min-width="120">
        <template slot-scope="{row}">
          <el-button size="small" type="warning" @click="deleteSchool(row)">删除</el-button>
        </template>
      </el-table-column>
  </el-table>
  <el-button type="warning" @click="delText" style="margin-left: 10px;margin-top:20px;">批量删除所选</el-button>
      <!-- 分页 -->
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange_have" @current-change="handleCurrentChange_have" :current-page.sync="haveSchools.pageNo" :page-sizes="[10,20,30,50]" :page-size="haveSchools.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total_have">
      </el-pagination>
    </div>
    </el-col>
    <el-col :span="2"></el-col>
    <el-col :span="11"> 
    <div class="line"><span style="margin-left:10px">选择关联高中：</span></div>
      <div class="filter-container" style="margin:20px 0">
        <span style="margin-left:10px">高中名称：</span>
        <el-input @keyup.enter.native="getNameList" style="width: 200px;" class="filter-item" placeholder="请输入高中名称" v-model="schoolLists.title" clearable></el-input>
        <span style="margin-left:10px">所属城市：</span>
        <el-cascader @keyup.enter.native="getNameList" change-on-select clearable placeholder="全部" expand-trigger="click" :options="areaCascadeOptions" v-model="schoolLists.areaId"></el-cascader>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        <!-- <el-button class="filter-item" style="margin-left: 10px;" type="success"  @click="have">关联所选高中</el-button> -->
      </div>
      <el-table
    ref="multipleTable"
    :data="schoolList"
    tooltip-effect="dark"
    style="width: 100%"
    @selection-change="handleSelectionChange_all">
    <el-table-column
      type="selection"
      width="100">
    </el-table-column>
    <el-table-column
      label="高中ID"
      width="120">
      <template slot-scope="scope">{{ scope.row.id }}</template>
    </el-table-column>
    <el-table-column
      prop="title"
      label="高中名称"
      width="300">
    </el-table-column>
    <el-table-column
      prop="areaNames"
      label="所属地区"
      show-overflow-tooltip>
    </el-table-column>
  </el-table><br>
  <el-button class="filter-item" style="margin-left: 10px;" type="primary"  @click="have">关联所选高中</el-button>
      <!-- 分页 -->
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange_all" @current-change="handleCurrentChange_all" :current-page.sync="schoolLists.pageNo" :page-sizes="[10,20,30,50]" :page-size="schoolLists.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total_all">
      </el-pagination>
    </div>
    </el-col>
    </el-row>
    </el-dialog>
    
  </div>
</template>

<script>
import { highSchoolByPage, haveSchools, addNewHighSchool, deleteSchool, searchMarketer } from '@/api/marketer'
import { getList } from '@/api/school'
import { getNameList } from '@/api/highSchool'
// import { getToken } from '@/utils/auth' // 验权
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'list',
  data() {
    return {
      schools: [],
      schoolList : [],
      haveSchool : [],
      multipleSelection_all : [], // 剔除重复选择关联的学校id之后的有效学校id数组
      options:[], // 选择的学校id数组
      multipleSelection_have : [], // 已经关联的学校的id数组
      areas: [],
      schoolOption: 0,
      areaOption: [],
      list: null,
      total: null,
      total_all: null,
      total_have: null,
      listLoading: true,
      listQuery: {
        areaId: null,
        areaIds: [],
        pageNo: 1,
        pageSize: 10,
        schoolId: null,
        title: '',
        nickname:null,
        marketerMobile: null,
        marketerName: ''
      },
      schoolLists :{
        title:'',
        areaId:null,
        pageNo: 1,
        pageSize: 10
      },
      haveSchools :{
        marketerId : null,
        pageNo: 1,
        pageSize: 10,
        pages:null
      },
      temp: {
        labels: []
      },
      dialogFormVisible: false,
      rules: {
        areaId: [{ required: true, message: '请选择所属地区', trigger: 'change' }],
        schoolId: [{ required: true, message: '请选择所属学校', trigger: 'change' }],
        userType: [{ required: true, message: '请选择用户类型', trigger: 'change' }]
      },
      tableKey: 0,
      showAllDel: false,
      schoolOptions: [],
      isSchoolLoading: false
    }
  },
  created() {
    this.getLists()
    this.GetAreaCascadeOptions()
  },

  computed: {
    ...mapGetters(['areaCascadeOptions'])
  },
  methods: {
    // 选择关联高中的结果
    handleSelectionChange_all(val) {
      const arr = []
      val.forEach(item => {
        arr.push(item.id)
      })
      // 做个判断，如果已经关联过了，则剔除学校id
      const haveBeen = []
      this.haveSchool.forEach(item => {
        haveBeen.push(item.schoolId)
      })
      var tempArray1 = []//临时数组1
      var tempArray2 = []
      for(var i = 0; i < haveBeen.length; i++){
        tempArray1[haveBeen[i]] = true//将数array2 中的元素值作为tempArray1 中的键，值为true；
      }
      for(var i = 0; i < arr.length; i++){
        if(!tempArray1[arr[i]]){
          tempArray2.push(arr[i])//过滤array1 中与array2 相同的元素；
        }
      }
      this.options = arr
      this.multipleSelection_all = tempArray2
    },
    // 选择要删除高中的结果
    handleSelectionChange_have(val) {
      const arr = []
      val.forEach(item => {
        arr.push(item.schoolId)
      })
      this.multipleSelection_have = arr
    },
    // 取消打钩的选择
    toggleSelection() {
      this.$refs.multipleTable.clearSelection()
    },

    // 关联选择的高中
    have(){
      const params = {
        marketerId : this.haveSchools.marketerId,
        highSchoolIds : this.multipleSelection_all
      }
      if(this.options.toString() == ''){
        this.$message({
          title: '失败',
          message: '请选择需要关联的学校',
          type: 'error',
          duration: 2000
        })
        return
      }else if(this.multipleSelection_all.length == 0 || this.options.toString() != this.multipleSelection_all.toString()){
        this.$message({
          title: '失败',
          message: '重复关联学校，请检查',
          type: 'error',
          duration: 2000
        })
        return
      }
      addNewHighSchool(params).then(res => {
        if(res.code == 0) {
          this.haveSchoolss()
          this.$notify({
            title: '成功',
            message: '关联学校成功',
            type: 'success',
            duration: 2000
          })
        }else{
          this.$message({
            title: '失败',
            message: '关联学校失败',
            type: 'error',
            duration: 2000
          })
        }
      }).catch(err => {})
      this.toggleSelection()
    },
    // 单个点击删除高中按钮

    deleteSchool(row){
      const params = {
        marketerId : this.haveSchools.marketerId,
        highSchoolIds : [row.schoolId]
      }
      deleteSchool(params).then(res => {
        if(res.code == 0) {
          if(this.total_have % 10 == 1 && this.haveSchools.pages == this.haveSchools.pageNo){
            this.haveSchools.pageNo -= 1
            if (this.haveSchools.pageNo == 0){
              this.haveSchools.pageNo = 1
            }
          }
          this.haveSchoolss()
          this.$notify({
            title: '成功',
            message: '删除学校成功',
            type: 'success',
            duration: 2000
          })
        }else{
          this.$message({
            title: '失败',
            message: '删除学校失败',
            type: 'error',
            duration: 2000
          })
        }
      }).catch(err => {})
    },
    // 批量删除高中
    delText(){
      const params = {
        marketerId : this.haveSchools.marketerId,
        highSchoolIds : this.multipleSelection_have
      }
      if(this.multipleSelection_have.toString() == ''){
        this.$message({
          title: '失败',
          message: '请选择学校后再批量删除',
          type: 'error',
          duration: 2000
        })
        return
      }
      deleteSchool(params).then(res => {
        if(res.code == 0) {
          if(this.multipleSelection_have.length == this.total_have % 10 && this.haveSchools.pages == this.haveSchools.pageNo){
            this.haveSchools.pageNo -= 1
            if (this.haveSchools.pageNo == 0){
              this.haveSchools.pageNo = 1
            }
          }
          this.haveSchoolss()
          this.$notify({
            title: '成功',
            message: '删除学校成功',
            type: 'success',
            duration: 2000
          })
        }else{
          this.$message({
            title: '失败',
            message: '删除学校失败',
            type: 'error',
            duration: 2000
          })
        }
      }).catch(err => {})
      this.toggleSelection()
    },
    // 映射 Actions
    ...mapActions(['GetAreaCascadeOptions']),

    // 市场人员列表
    getLists() {
      this.schoolLists.areaId = null
      this.schoolLists.title = ''
      this.listLoading = true
      const params = this.listQuery
      highSchoolByPage(params).then(response => {
        const { code, data: { total, list = [] } } = response
        if (code == 0) {
          this.total = total
          this.list = list
          this.listLoading = false
        }
      }).catch(err => {})
    },

    // 通过高中名称和地区模糊查询
    getNameList(){
      this.listLoading = true
      const params = {
        title: this.schoolLists.title.trim(),
        areaId: this.schoolLists.areaId == null ? null : this.schoolLists.areaId[this.schoolLists.areaId.length - 1],
        pageNo: this.schoolLists.pageNo,
        pageSize: this.schoolLists.pageSize
      }
      getList(params).then(res => {
        if(res.code == 0){
          this.schoolList = res.data.list
          this.total_all = res.data.total
          this.schoolLists.pageSize = res.data.pageSize
          this.listLoading = false
        }
      }).catch(err => {})
    },
    // 搜索高中
    handleFilter() {
      this.schoolLists.pageNo = 1
      this.schoolLists.pageSize = 10
      this.getNameList()
    },
    //市场人员分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getLists()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getLists()
    },
    // 所有学校列表分页
    handleCurrentChange_all(val) {
      this.schoolLists.pageNo = val
      this.getNameList()
    },
    handleSizeChange_all(val) {
      this.schoolLists.pageSize = val
      this.getNameList()
    },
    // 已经关联高中分页
    handleSizeChange_have(val) {
      this.haveSchools.pageSize = val
      this.haveSchoolss()
    },
    handleCurrentChange_have(val) {
      this.haveSchools.pageNo = val
      this.haveSchoolss()
    },
    // 获得已经关联的高中
    haveSchoolss(){
      // this.haveSchools.marketerId = row.marketerId
      const par = {
        marketerId : this.haveSchools.marketerId,
        pageNo: this.haveSchools.pageNo,
        pageSize: this.haveSchools.pageSize
      }
      haveSchools(par).then(res => {
        if(res.code == 0) {
          this.haveSchool = res.data.list
          this.total_have = res.data.total
          this.haveSchools.pages = res.data.pages
        }
      })
    },
    // 点击编辑按钮
    handleModifyStatus(row) {
      this.haveSchools.pageNo = 1
      this.schoolLists.pageNo = 1
      this.schoolLists.title = ''
      this.schoolLists.areaId = null
      this.getNameList()
      this.haveSchools.marketerId = row.marketerId
      // 获得已经关联的高中
      this.haveSchoolss()
      this.dialogFormVisible = true
    },

    handleDelete(idx, row) {
      // const { id } = row
      // delId(id).then(response => {
      //   const { code } = response
      //   if (code == 0) {
      //     this.$notify({
      //       title: '成功',
      //       message: '删除资讯成功',
      //       type: 'success',
      //       duration: 2000
      //     })
      //     // const index = this.list.indexOf(idx)
      //     this.list.splice(idx, 1)
      //     this.total--
      //   } else {
      //     this.$notify({
      //       title: '失败',
      //       message: '删除资讯失败',
      //       type: 'error',
      //       duration: 2000
      //     })
      //   }
      // })
    },
    handleRefresh() {
      this.list = null
      this.total = null
      this.listQuery.pageNo = 1
      this.getLists()
    },
    // 通过电话和姓名搜索市场人员
    searchMarketers(){
      const params = this.listQuery
      searchMarketer(params).then(res => {
        if(res.code == 0) {
          this.total = res.data.total
          this.list = res.data.list
          this.listLoading = false
        }
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.icon-ctx {
  width: 160px;
  height: 80px;
  overflow: hidden;
  margin: 0 auto;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.app-container {
  padding: 20px;
}
.pagination-container {
  margin-top: 30px;
}
.line{
  width: 100%;
  height: 40px;
  margin-top: 20px;
  text-align: center;
  line-height: 40px;
  font-size: 20px;
  color: #000;
}
.content{
  display: flex;
  :nth-child(1){
    flex: 5;
  }
  :nth-child(2){
    flex: 1;
  }
  :nth-child(3){
    flex: 5;
  }
}

</style>